<?php

use Medoo\Medoo;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;


$client = new GuzzleHttp\Client();
//https://campaigns.digitalvolvo.com/campaign/statistic/api/web/v1/apiservice/dealers/list.php
//https://campaigns.digitalvolvo.com/campaign/statistic/api/web/v1/apiservice/dealers/volvo-select.php
$res = $client->request('GET',
    'https://campaigns.digitalvolvo.com/campaign/statistic/api/web/v1/apiservice/dealers/list.php'
    , [
        'headers' => [
            'Referer' => 'https://campaigns.digitalvolvo.com/campaign/finance/campaign_test/dealers_test5/',
            'Accept' => 'application/json, text/plain, */*',
        ]
    ]);
$html = (string)$res->getBody();

$ok = preg_match('/"Province":\{(.*)\}\}\}/U', $html, $m);


if ($ok) {
    $db = new Medoo($config);
    $db->delete('tDealer', ['sBrand' => '沃尔沃']);
    $data = json_decode('{' . $m[1] . '}', true);
    foreach ($data as $province) {
        foreach ($province as $dealer) {
            $db->insert('tDealer', [
                'sDealerName' => $dealer['DealerName'],

                'sBrand' => '沃尔沃',
                'sProvince' => $dealer['Province'],
                'sCity' => $dealer['City'],
                'sAddress' => $dealer['Address'],
                'sSaleCall' => $dealer['SaleTel'],
                'sLatitude' => $dealer['Latitude'],
                'sLongitude' => $dealer['Longitude'],
                'dUpdateTime' => Medoo::raw('now()'),
                'sManufacturer' => '沃尔沃',
            ]);
            echo "{$dealer['DealerName']}完成" . PHP_EOL;
        }
    }
    echo '爬虫完成' . PHP_EOL;
}

